package com.leyou.item.controller;


import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.TbCategory;
import com.leyou.item.service.TbCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("category")
//@CrossOrigin默认情况下，@CrossOrigin允许在@RequestMapping注解中指定的所有源和HTTP方法
public class CategoryController {

    @Autowired
    private TbCategoryService categoryService;
    /*
    * url:/of/parent
    * param：pid 父节点 默认 pid=0;
    * */
    @GetMapping("/of/parent")
    public ResponseEntity<List<CategoryDTO>> queryListByParent(@RequestParam(value = "pid",defaultValue = "0")Long pid){

        /*自定义查询方法queryListByParent()*/
         List<CategoryDTO>  categoryDTOList=categoryService.queryListByParent(pid);

         return ResponseEntity.status(HttpStatus.OK).body(categoryDTOList);
    }
    @GetMapping("/of/brand")
    public ResponseEntity<List<CategoryDTO>> queryListByBrandId(@RequestParam(value = "id",required = true) Long id){

     List<CategoryDTO> categoryDTOList=categoryService.queryListByBrandId(id);

     return  ResponseEntity.status(HttpStatus.OK).body(categoryDTOList);
    }

    @GetMapping("/list")
    public ResponseEntity<List<CategoryDTO>> findCategoryByIds(@RequestParam("ids")List<Long> ids){
        Collection<TbCategory> tbCategories = categoryService.listByIds(ids);
        /*对象转换*/
        if(CollectionUtils.isEmpty(tbCategories)){
            throw  new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        /*采用stream
        * map(T -> R) 映射 ：1.将T类型数据，转化为 R类型的数据，自定义转换函数
        *                   2.将T类型数据中的某个属性，进行转换并可收集成新的流
        * 将流中的每一个元素 T 映射为 R（类似类型转换）
        * 对于Stream中包含的元素使用   给定的转换函数   进行转换操作，
        * 新生成的Stream只包含转换生成的元素
        * collect()收集
            toList
            toSet
            toCollection
            toMap
            collect(joining(",")字符串连接
        * */
        List<CategoryDTO> categoryDTOList = tbCategories.stream().map(tbCategory -> {
            return BeanHelper.copyProperties(tbCategory, CategoryDTO.class);
        }).collect(Collectors.toList());

        return ResponseEntity.status(HttpStatus.OK).body(categoryDTOList);
    }
}
